# -*- python -*-
import os
import sys
import string
Import('*')

##### Construct the tar.gz which needed by rootfs.
## include: 
#           #bindir/root.step1.tar.gz
#           #bindir/root.bootscripts.tar.gz
#           #bindir/kmodules-x.xx.xx.tar.bz2
#           #bindir/mi-vmlinuz-x.xx.xx  (needed by iso)
SConscript('buildpkg/SConscript')

##### mirootfs.gz
## #result/mirootfs.gz <- 
#               #bindir/root.step1.tar.gz
#               #bindir/root.src.tar.gz
#               #bindir/root.bootscripts.tar.gz
#               #bindir/kmodules-x.xx.xx.tar-bz2
class MirootfsMaker(PkgMaker.StepMaker):
    target_list = ['result/mirootfs.gz']
    ROOT = 'tmp/mi.rootfs'
    steps = [
             #'init_dir',
             'extract_bins',
             'run_post_scripts',
             'mkcramfs',
             ]

    def init_dir(self):
        # Check if $ROOT is your mount dir.
        if self.ROOT.startswith('/') or len(self.ROOT) == '':
            os.write(2, '%s can not start with / or blank.' % self.ROOT)
            sys.exit(-1)
        f = file('/proc/mounts')
        l = f.readline()
        ltodir = len('$ROOT')
        dangeous_mount = None
        while l:
            pieces = string.split(l, ' ')
            if pieces[1][:ltodir] == '$ROOT':
                os.write(2, 'DANGEOUS MOUNT: [%s]\n' % str(pieces[:2]))
                dangeous_mount = 'true'
            l = f.readline()
        if dangeous_mount:
            os.write(2, 'Please umount the previous mounts firstly!\n')
            sys.exit(-1)

        cmds = [getSudoSh('rm -rf $ROOT'),
                'mkdir -p $ROOT']
        return [], cmds

    def extract_bins(self):
        toextract = ['bindir/root.step1.tar.gz',
                     'bindir/root.src.tar.gz',
                     'bindir/root.bootscripts.tar.gz',
                     'bindir/kmodules-${mikernelver}.tar.bz2']

        #if mi_config.useudev:
        #    toextract.append('bindir/udev-${udev_version}.tar.bz2')
        mkstep2_script = 'scripts/mkstep2.py'
        # Use sudo, because we use root to create the root.step1.tar.gz .
        # If we use other user to extract the root.step1.tar.gz, the files
        # permision will change.(We create the root.step1.tar.gz and other
        # rootfs tar packages use root user, only correspond with the
        # files' permision, so be careful with your system.:P )
        cmds = [getSudoSh( '$pythonbin %s $udev_arg %s' % \
                (mkstep2_script,
                 ' '.join(toextract)) )]
        return toextract + [mkstep2_script], cmds

    def run_post_scripts(self):
        # Add some directory, nodes, links and check privilege.
        os.chmod('buildpkg/post_scripts/commands.sh', 0777)
        cmds = [getSudoSh("buildpkg/post_scripts/commands.sh $ROOT"),
                getSudoSh("install -m 777 buildpkg/post_scripts/commands_chroot.sh $ROOT"),
                getSudoSh('/usr/sbin/chroot $ROOT /commands_chroot.sh'),
                getSudoSh('rm $ROOT/commands_chroot.sh'),
            ]
        return [], cmds

    def mkcramfs(self):
        cmds = ['mkdir -p result',
                'cd $ROOT && %s' % getSudoSh("find . | cpio -o -H newc | gzip -9 > $TARGET.abspath")]
        return [], cmds

mirootfs = MirootfsMaker(env)
mirootfs.make()

